local Bag={["used"]=0,["total"]=0,["load"]=0};

function XBarBag_OnEvent(this,event)
--	ChatFrame1:AddMessage("XBar-Bag : "..event);
	if (event=="LOADING_END") then
		this:RegisterEvent("PLAYER_BAG_CHANGED");
		this:RegisterEvent("PLAYER_INVENTORY_CHANGED");
	end
 
	Bag["used"],Bag["total"]=GetBagCount();
	Bag["load"]=math.ceil((Bag["used"]/Bag["total"])*100);
	if (Bag["load"]>=90) then
		Bag["used"]="|cffFF0000"..Bag["used"].."|r";
		Bag["load"]="|cffFF0000"..Bag["load"].."|r";
		Bag["total"]="|cffFF0000"..Bag["total"].."|r";
	elseif (Bag["load"]>=80) then
		Bag["used"]="|cffFF7700"..Bag["used"].."|r";
		Bag["load"]="|cffFF7700"..Bag["load"].."|r";
		Bag["total"]="|cffFF7700"..Bag["total"].."|r";
	elseif (Bag["load"]>=70) then
		Bag["used"]="|cffFFFF00"..Bag["used"].."|r";
		Bag["load"]="|cffFFFF00"..Bag["load"].."|r";
		Bag["total"]="|cffFFFF00"..Bag["total"].."|r";
	else
		Bag["used"]="|cffFFFFFF"..Bag["used"].."|r";
		Bag["load"]="|cffFFFFFF"..Bag["load"].."|r";
		Bag["total"]="|cffFFFFFF"..Bag["total"].."|r";
	end
--	Output
	local usrtxt={[1]=XBar["BagV1"],[2]=XBar["BagV2"]};
	local output="";
	for i=1,2 do
		if (usrtxt) and (usrtxt[i]~="") then
			usrtxt[i],_=XBar_StrReplace(usrtxt[i],"%[USED%]",Bag["used"]);
			usrtxt[i],_=XBar_StrReplace(usrtxt[i],"%[TOTAL%]",Bag["total"]);
			usrtxt[i],_=XBar_StrReplace(usrtxt[i],"%[LOAD%]", Bag["load"]);
		end
	end
	if (XBar["BagT1"]==true) then output=usrtxt[1]; end
	if (XBar["BagT2"]==true) then
		if (XBar["BagT1"]==true) then output=output.."\n"..usrtxt[2]; else output=usrtxt[2]; end
	end
	XBarBag_F_Text:SetText(output);
--	EoL
end
